package com.toogu.mazhangmen.sdk;

import android.graphics.Bitmap;
import android.net.DhcpInfo;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiInfo;
import android.os.Bundle;
import android.os.Message;
import android.text.format.Formatter;
import android.util.Log;
import android.view.ViewGroup;

import com.basic.G;
import com.lib.EUIMSG;
import com.lib.FunSDK;
import com.lib.IFunSDKResult;
import com.lib.MsgContent;
import com.lib.SDKCONST;
import com.lib.app.APP_JsonConfig;
import com.lib.sdk.bean.DSTimeBean;
import com.lib.sdk.bean.DayLightTimeBean;
import com.lib.sdk.bean.DefaultConfigBean;
import com.lib.sdk.bean.EncyptChipInfoBean;
import com.lib.sdk.bean.HandleConfigData;
import com.lib.sdk.bean.JsonConfig;
import com.lib.sdk.bean.LocationBean;
import com.lib.sdk.bean.PtzCtrlInfoBean;
import com.lib.sdk.bean.StringUtils;
import com.lib.sdk.bean.SystemFunctionBean;
import com.lib.sdk.bean.SystemInfoBean;
import com.lib.sdk.bean.SystemInfoExBean;
import com.lib.sdk.bean.TimeZoneBean;
import com.lib.sdk.bean.VideoWidgetBean;
import com.lib.sdk.struct.SDBDeviceInfo;
import com.lib.sdk.struct.SDK_CONFIG_NET_COMMON_V2;
import com.lib.sdk.struct.SDK_ChannelNameConfigAll;
import com.manager.account.AccountManager;
import com.manager.base.BaseManager;
import com.manager.db.DevDataCenter;
import com.manager.db.XMDevInfo;
import com.manager.device.IDeviceManager;
import com.manager.device.bind.qrcode.presenter.QRConfigResultManager;
import com.manager.device.config.DevConfigInfo;
import com.manager.device.config.DevConfigManager;
import com.manager.device.fisheye.FishEyeConfig;
import com.manager.device.media.MediaManager;
import com.manager.device.media.attribute.PlayerAttribute;
import com.manager.device.media.attribute.RecordPlayerAttribute;
import com.manager.device.media.playback.CloudRecordManager;
import com.manager.device.media.playback.DevRecordManager;
import com.manager.device.media.playback.RecordManager;
import com.utils.XUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.TimeZone;

import static com.lib.app.APP_JsonConfig.MODIFY_DEV_PWD_FROM_DEV;

/**
 * Created by hws on 2018-04-25.
 */

public class DeviceManager2 extends BaseManager implements IDeviceManager,
        IFunSDKResult, DevDataCenter.OnDevDataCenterListener {
    public static final int OPERA_LOGIN_DEV = 0;
    public static final int OPERA_GET_CONFIG_DEV = 1;
    public static final int OPERA_SET_CONFIG_DEV = 2;
    public static final int OPERA_CMD = 3;
    public static final int DEVICE_LINK_ROUTER_SUCCESS = 244;//在路由器下查询找到设备时的回调值
    public static final int RECEIVE_ROUTER_INFORMATION_SUCCESS = 1;//设备成功接收到WiFi信息的回调返回值
    public static final int UPGRADE_TYPE_NONE = 0;//本地选择文件更新
    public static final int UPGRADE_TYPE_CLOUD = 1;//设备连接升级服务器升级
    public static final int UPGRADE_TYPE_FILE_DOWNLOAD = 2;//本地升级,但升级文件还没有下载下来
    public static final int UPGRADE_TYPE_LOCAL_FILE = 3;//本地升级,升级文件已经下载下来了

    private static DeviceManager2 instance;
    private AccountManager accountManager;
    private DevDataCenter devDataCenter;
    private List<XMDevInfo> lanDevList;
    private HashMap<Integer, String> devIdMap;
    private HashMap<String, DevConfigInfo> listenerMap;
    private int userId;
    private int timeOut = 5000;//超时时间 默认是5秒
    private com.manager.device.DeviceManager.OnSearchLocalDevListener onSearchLocalDevListener;
    private com.manager.device.DeviceManager.OnQuickSetWiFiListener onQuickSetWiFiListener;
    private com.manager.device.DeviceManager.OnDevWiFiSetListener onDevWiFiSetListener;
    private com.manager.device.DeviceManager.OnDevUpgradeListener onDevUpgradeListener;
    private DeviceManager2() {
        accountManager = AccountManager.getInstance();
        devDataCenter = DevDataCenter.getInstance(this);
        userId = FunSDK.GetId(userId, this);
        devIdMap = new HashMap<>();
        listenerMap = new HashMap<>();
    }

    public static DeviceManager2 getInstance() {
        if (null == instance) {
            instance = new DeviceManager2();
        }
        return instance;
    }

    @Override
    public boolean init() {
        if (!accountManager.isInit()) {
            accountManager.localLogin(null,null);
        }
        userId = FunSDK.GetId(userId, this);
        return true;
    }

    @Override
    public boolean init(String initType) {
        return false;
    }

    @Override
    public void unInit() {
        accountManager.unInit();
        FunSDK.UnRegUser(userId);
        userId = -1;
    }

    @Override
    public boolean loginDev(String devId, com.manager.device.DeviceManager.OnDevManagerListener listener) {
        if (null == devId) {
            return false;
        }
        init();
        listenerMap.put(APP_JsonConfig.DEV_LOGIN + devId, DevConfigInfo.create(listener));
        int seq = devId.hashCode();
        devIdMap.put(seq, devId);
        FunSDK.DevGetConfigByJson(userId, devId, JsonConfig.SYSTEM_INFO,
                1024, -1, timeOut, seq);
        return true;
    }

    @Override
    public boolean loginDev(String devId, String userName, String password, com.manager.device.DeviceManager.OnDevManagerListener listener) {
        if (null == devId) {
            return false;
        }
        init();
        listenerMap.put(APP_JsonConfig.DEV_LOGIN + devId, DevConfigInfo.create(listener));
        int seq = devId.hashCode();
        devIdMap.put(seq, devId);
        if (devDataCenter.isDevExist(devId)) {
            FunSDK.DevSetLocalPwd(devId, userName, password);
        }

        FunSDK.DevGetConfigByJson(userId, devId, JsonConfig.SYSTEM_INFO, 1024, -1, timeOut, seq);
        return true;
    }

    @Override
    public void logoutDev(String devId) {
        if (null == devId) {
            return;
        }
        init();
        listenerMap.remove(APP_JsonConfig.DEV_LOGIN + devId);
        int seq = devId.hashCode();
        devIdMap.put(seq, devId);
        FunSDK.DevLogout(userId, devId, seq);
    }

    @Override
    public void getChannelInfo(String devId, com.manager.device.DeviceManager.OnDevManagerListener listener) {
        if (null == devId) {
            return;
        }

        init();
        listenerMap.put(APP_JsonConfig.DEV_GET_CHANNEL_INFO + devId, DevConfigInfo.create(listener));
        int seq = devId.hashCode();
        devIdMap.put(seq, devId);

        FunSDK.DevGetChnName(userId,devId,"","",seq);
    }

    /**
     * 只有支持DSS的设备才支持该方法
     * @param devId
     */
    @Override
    public int getChannelCount(String devId) {
        if (null == devId) {
            return 0;
        }

        return FunSDK.GetDevChannelCount(devId);
    }

    @Override
    public com.manager.device.media.monitor.MonitorManager createMonitorPlayer(ViewGroup playView) {
        return  new com.manager.device.media.monitor.MonitorManager(playView, new PlayerAttribute());
    }

    @Override
    public com.manager.device.media.monitor.MonitorManager createMonitorPlayer(ViewGroup playView, String devId) {
        return new com.manager.device.media.monitor.MonitorManager(playView, new PlayerAttribute(devId));
    }

    @Override
    public com.manager.device.media.monitor.MonitorManager createMonitorPlayer(ViewGroup playView, PlayerAttribute attribute) {
        if (attribute == null) {
            return null;
        }
        return new com.manager.device.media.monitor.MonitorManager(playView,attribute);
    }

    @Override
    public com.manager.device.media.monitor.MonitorManager[] createMonitorPlayers(ViewGroup[] playViews, PlayerAttribute[] attributes, int count) {
        if (count <= 0) {
            return null;
        }
        com.manager.device.media.monitor.MonitorManager[] monitorManagers = new com.manager.device.media.monitor.MonitorManager[count];
        for (int i = 0; i < count; ++i) {
            monitorManagers[i] = new com.manager.device.media.monitor.MonitorManager(playViews[i],attributes[i]);
        }
        return monitorManagers;
    }

    @Override
    public RecordManager createRecordPlayer(ViewGroup playView, String devId, int mediaType) {
        if (mediaType == MediaManager.PLAY_CLOUD_PLAYBACK) {
            return new CloudRecordManager(playView,new RecordPlayerAttribute(devId));
        }else {
            return new DevRecordManager(playView, new RecordPlayerAttribute(devId));
        }
    }

    @Override
    public void setLocalDevPwd(String devId, String pwd) {
        FunSDK.DevSetLocalPwd(devId,
                "admin",
                pwd);
    }

    @Override
    public void modifyDevPwd(String devId, String userName, String oldPwd,String newPwd, com.manager.device.DeviceManager.OnDevManagerListener listener) {
        init();
        DevConfigInfo resultInfo = DevConfigInfo.create(listener);
        Bundle bundle = new Bundle();
        bundle.putString("userName", userName);
        bundle.putString("password", newPwd);
        resultInfo.setCfgInfo(bundle);
        listenerMap.put(MODIFY_DEV_PWD_FROM_DEV + devId, resultInfo);
        oldPwd = FunSDK.DevMD5Encrypt(oldPwd);
        newPwd = FunSDK.DevMD5Encrypt(newPwd);
        JSONObject json = new JSONObject();
        try {
            json.put("EncryptType", "MD5");
            json.put("NewPassWord", newPwd);
            json.put("PassWord", oldPwd);
            json.put("SessionID", "0x6E472E78");
            json.put("UserName", "admin");
            if (json != null) {
                int seq = devId.hashCode();
                devIdMap.put(seq, devId);
                FunSDK.DevSetConfigByJson(userId, devId, MODIFY_DEV_PWD_FROM_DEV,
                        json.toString(), -1, 10000, seq);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }

    @Override
    public void modifyDevName(final String devId, final String devName, final com.manager.device.DeviceManager.OnDevManagerListener listener) {
        init();
        if (listener != null) {
            DevConfigInfo resultInfo = DevConfigInfo.create(listener);
            resultInfo.setCfgInfo(devName);
            resultInfo.setLastConfig(false);
            listenerMap.put(APP_JsonConfig.MODIFY_DEV_NAME_FROM_DEV + devId, resultInfo);
            int seq = devId.hashCode();
            devIdMap.put(seq, devId);
            FunSDK.DevGetConfigByJson(userId, devId, JsonConfig.CFG_WIDEOWIDGET, 1024, 0, timeOut, seq);
        }
    }

    @Override
    public DevConfigManager getDevConfigManager(String devId) {
        return DevConfigManager.create(devId);
    }

    @Override
    public int getDevType(String devId) {
        init();
        return devDataCenter.getDevType(devId);
    }

    @Override
    public String getSerialNo(String devId) {
        init();
        return devDataCenter.getSerialNo(devId);
    }

    @Override
    public String getBuildTime(String devId, com.manager.device.DeviceManager.OnDevManagerListener listener) {
        init();
        return devDataCenter.getBuildTime(devId, listener);
    }

    @Override
    public String getHardWare(String devId, com.manager.device.DeviceManager.OnDevManagerListener listener) {
        init();
        return devDataCenter.getHardWare(devId, listener);
    }

    @Override
    public int getDigChannel(String devId, com.manager.device.DeviceManager.OnDevManagerListener listener) {
        init();
        return devDataCenter.getDigChannel(devId, listener);
    }

    @Override
    public int getExtraChannel(String devId, com.manager.device.DeviceManager.OnDevManagerListener listener) {
        init();
        return devDataCenter.getExtraChannel(devId, listener);
    }

    @Override
    public int getVideoInChannel(String devId, com.manager.device.DeviceManager.OnDevManagerListener listener) {
        init();
        return devDataCenter.getVideoInChannel(devId, listener);
    }

    @Override
    public int getTalkInChannel(String devId, com.manager.device.DeviceManager.OnDevManagerListener listener) {
        init();
        return devDataCenter.getTalkInChannel(devId, listener);
    }

    @Override
    public int getAlarmInChannel(String devId, com.manager.device.DeviceManager.OnDevManagerListener listener) {
        init();
        return devDataCenter.getAlarmInChannel(devId, listener);
    }

    @Override
    public int getAlarmOutChannel(String devId, com.manager.device.DeviceManager.OnDevManagerListener listener) {
        init();
        return devDataCenter.getAlarmOutChannel(devId, listener);
    }

    @Override
    public int getCombineSwitch(String devId, com.manager.device.DeviceManager.OnDevManagerListener listener) {
        init();
        return devDataCenter.getCombineSwitch(devId, listener);
    }

    @Override
    public int getVideoOutChannel(String devId, com.manager.device.DeviceManager.OnDevManagerListener listener) {
        init();
        return devDataCenter.getVideoOutChannel(devId, listener);
    }

    @Override
    public int getAudioInChannel(String devId, com.manager.device.DeviceManager.OnDevManagerListener listener) {
        init();
        return devDataCenter.getAudioInChannel(devId, listener);
    }

    @Override
    public int getTalkOutChannel(String devId, com.manager.device.DeviceManager.OnDevManagerListener listener) {
        init();
        return devDataCenter.getTalkOutChannel(devId, listener);
    }

    @Override
    public String getUpdataTime(String devId, com.manager.device.DeviceManager.OnDevManagerListener listener) {
        init();
        return devDataCenter.getUpdataTime(devId, listener);
    }

    @Override
    public String getEncryptVersion(String devId, com.manager.device.DeviceManager.OnDevManagerListener listener) {
        init();
        return devDataCenter.getEncryptVersion(devId, listener);
    }

    @Override
    public String getDeviceRunTime(String devId, com.manager.device.DeviceManager.OnDevManagerListener listener) {
        init();
        return devDataCenter.getDeviceRunTime(devId, listener);
    }

    @Override
    public String getHardWareVersion(String devId, com.manager.device.DeviceManager.OnDevManagerListener listener) {
        init();
        return devDataCenter.getHardWareVersion(devId, listener);
    }

    @Override
    public String getSoftWareVersion(String devId, com.manager.device.DeviceManager.OnDevManagerListener listener) {
        init();
        return devDataCenter.getSoftWareVersion(devId, listener);
    }

    @Override
    public String getDeviceModel(String devId, com.manager.device.DeviceManager.OnDevManagerListener listener) {
        init();
        return devDataCenter.getDeviceModel(devId,listener);
    }

    @Override
    public String getMcuVersion(String devId, com.manager.device.DeviceManager.OnDevManagerListener listener) {
        init();
        return devDataCenter.getMcuVersion(devId,listener);
    }

    @Override
    public int getEncyptChipInfo(String devId, com.manager.device.DeviceManager.OnDevManagerListener listener) {
        init();
        return devDataCenter.getEncyptChipInfo(devId,listener);
    }

    @Override
    public int getNetConnectMode(String devId, com.manager.device.DeviceManager.OnDevManagerListener listener) {
        init();
        return devDataCenter.getNetConnectMode(devId,listener);
    }

    @Override
    public boolean isDontDewarpDevice(String devId) {
        String hardWare = devDataCenter.getHardWare(devId, null);
        String buildTime = devDataCenter.getBuildTime(devId, null);
        if (StringUtils.isStringNULL(hardWare) || StringUtils.isStringNULL(buildTime)) {
            return false;
        }

        for (String info : FishEyeConfig.dontDewarpDeviceInfo) {
            if (info.contains(hardWare) && info.contains(buildTime)) {
                return true;
            }
        }
        return false;
    }

    @Override
    public boolean getDevAbility(String devId, com.manager.device.DeviceManager.OnDevManagerListener listener, String... field) {
        init();
        return devDataCenter.getSystemFunctionItemValue(devId,listener,field);
    }

    @Override
    public void searchLanDevice(com.manager.device.DeviceManager.OnSearchLocalDevListener listener) {
        init();
        this.onSearchLocalDevListener = listener;
        FunSDK.DevSearchDevice(userId,0,0);
    }

    @Override
    public void startQuickSetWiFi(WifiInfo wifiInfo, ScanResult scanResult, DhcpInfo dhcpInfo, String pwd, com.manager.device.DeviceManager.OnQuickSetWiFiListener listener) {
        init();
        this.onQuickSetWiFiListener = listener;
        String ssid = XUtils.initSSID(wifiInfo.getSSID());
        int pwdType = XUtils.getEncrypPasswordType(scanResult.capabilities);
        if (pwdType == 3 && (pwd.length() == 10 || pwd.length() == 26)) {
            pwd = XUtils.asciiToString(pwd);
        }
        StringBuffer data = new StringBuffer();
        data.append("S:").append(ssid).append("P:").append(pwd).append("T:").append(pwdType);
        String submask, gateway, ip, dns1, dns2, mac;
        if (dhcpInfo.netmask == 0) {
            submask = "255.255.255.0";
        } else {
            submask = Formatter.formatIpAddress(dhcpInfo.netmask);
        }
        gateway = Formatter.formatIpAddress(dhcpInfo.gateway);
        ip = Formatter.formatIpAddress(dhcpInfo.ipAddress);
        dns1 = Formatter.formatIpAddress(dhcpInfo.dns1);
        dns2 = Formatter.formatIpAddress(dhcpInfo.dns2);
        mac = wifiInfo.getMacAddress();
        StringBuffer info = new StringBuffer();
        info.append("gateway:")
                .append(gateway)
                .append(" ")
                .append("ip:")
                .append(ip)
                .append(" ")
                .append("submask:")
                .append(submask)
                .append(" ")
                .append("dns1:")
                .append(dns1)
                .append(" ")
                .append("dns2:")
                .append(dns2)
                .append(" ")
                .append("mac:")
                .append(mac)
                .append(" ");
        int nGetType = 2;//mac 不为00:00:00:00的时候起作用
        FunSDK.DevStartAPConfig(userId, nGetType, ssid, data.toString(),
                info.toString(), gateway, pwdType, 0, mac, -1);
    }

    @Override
    public void startQuickSetWiFiByDevLogin(String devId,String ssid, String pwd, com.manager.device.DeviceManager.OnDevWiFiSetListener listener) {
        init();
        this.onDevWiFiSetListener = listener;
        FunSDK.DevStartWifiConfigByAPLogin(userId,devId,ssid,pwd,-1);
    }

    @Override
    public void startQuickSetWiFi(String ssid, String pwd) {
        init();
        StringBuffer data = new StringBuffer();
        data.append("S:").append(ssid).append("P:").append(pwd).append("T:");
        FunSDK.DevStartAPConfig(userId, 2, ssid, data.toString(),
                "", "", 0, 0, "", -1);
    }


    @Override
    public void stopQuickSetWiFi() {
        init();
        FunSDK.DevStopAPConfig();
    }

    @Override
    public Bitmap initDevToRouterByQrCode(String ssid, String wifiPwd, int pwdType, String macAddress, String ipAddress, com.manager.device.DeviceManager.OnDevWiFiSetListener listener) {
//        try {
//            QRConfigResultManager qrConfigResultManager = QRConfigResultManager.getInstance();
//            qrConfigResultManager.setOnDevWiFiSetListener(listener);
//            String randomUuid = qrConfigResultManager.getQRConfigRandomUuid();
//            if (pwdType == 3 && (wifiPwd.length() == 10 || wifiPwd.length() == 26)) {
//                wifiPwd = XUtils.asciiToString(wifiPwd);
//            }
//            String[] result = ipAddress.split("\\.");
//            StringBuilder stringBuilder = new StringBuilder();
//            stringBuilder.append("S:").append(ssid).append("\n")
//                    .append("P:").append(wifiPwd).append("\n")
//                    .append("E:").append(pwdType).append("\n")
//                    .append("M:").append(macAddress).append("\n")
//                    .append("I:").append(result[result.length - 1]).append("\n")
//                    .append("B:").append(randomUuid).append("\n");
//            String qrCodeInfo = stringBuilder.toString();
//            return XUtils.createQRCodeBitmap(G.ToString(qrCodeInfo.getBytes("UTF-8"), "ISO-8859-1"),800, null);
//        }catch (Exception e) {
//            e.printStackTrace();
//        }
        return null;
    }

    @Override
    public void startDevToRouterByQrCode() {
        QRConfigResultManager qrConfigResultManager = QRConfigResultManager.getInstance();
        String randomUuid = qrConfigResultManager.getQRConfigRandomUuid();
        qrConfigResultManager.getQRConfigDevInfo(randomUuid);
    }

    @Override
    public void stopDevToRouterByQrCode() {
        QRConfigResultManager.getInstance().stopGetQRConfigDevInfo();
    }

    @Override
    public void unInitDevToRouterByQrCode() {
        QRConfigResultManager.getInstance().releaseGetQRConfigDevInfo();
    }

    @Override
    public List<XMDevInfo> getLanDevice() {
        return lanDevList;
    }

    @Override
    public boolean devPTZControl(PtzCtrlInfoBean ptzCtrlInfoBean, com.manager.device.DeviceManager.OnDevManagerListener listener) {
        if (ptzCtrlInfoBean != null) {
            int result = FunSDK.DevPTZControl(userId, ptzCtrlInfoBean.getDevId(),
                    ptzCtrlInfoBean.getChnId(), ptzCtrlInfoBean.getPtzCommandId(),
                    ptzCtrlInfoBean.isStop() ? SDKCONST.Switch.Open : SDKCONST.Switch.Close,
                    ptzCtrlInfoBean.getSpeed(), ptzCtrlInfoBean.getSeq());
            return (result == 1);
        }
        return false;
    }

    @Override
    public void syncDevTimeZone(String devId, int timeZone, com.manager.device.DeviceManager.OnDevManagerListener listener) {
        init();
        if (listener != null) {
            DevConfigInfo resultInfo = DevConfigInfo.create(listener);
            resultInfo.setLastConfig(false);
            listenerMap.put(APP_JsonConfig.SYNC_DEV_TIME_ZONE + devId, resultInfo);
            int seq = devId.hashCode();
            devIdMap.put(seq, devId);
            TimeZoneBean timeZoneBean = new TimeZoneBean();
            timeZoneBean.timeMin = timeZone;
            timeZoneBean.FirstUserTimeZone = 0;
            FunSDK.DevSetConfigByJson(userId, devId, JsonConfig.SYSTEM_TIMEZONE,
                    HandleConfigData.getSendData(JsonConfig.SYSTEM_TIMEZONE,
                            "0x1", timeZoneBean),
                    -1, timeOut, seq);
            FunSDK.DevGetConfigByJson(userId,devId, JsonConfig.GENERAL_LOCATION,
                    1024,-1,timeOut,seq);
        }
    }

    @Override
    public void syncDevTime(String devId, String time, com.manager.device.DeviceManager.OnDevManagerListener listener) {
        init();
        if (listener != null) {
            int seq = devId.hashCode();
            devIdMap.put(seq, devId);
            listenerMap.put(JsonConfig.OPTIME_SET + devId, DevConfigInfo.create(listener));
            FunSDK.DevSetConfigByJson(userId, devId, JsonConfig.OPTIME_SET,
                    HandleConfigData.getSendData(JsonConfig.OPTIME_SET, "0x00000001", time),
                    -1, timeOut, seq);
        }
    }

    @Override
    public void resetDevConfig(String devId, com.manager.device.DeviceManager.OnDevManagerListener listener) {
        init();
        if (listener != null) {
            int seq = devId.hashCode();
            devIdMap.put(seq, devId);
            listenerMap.put(JsonConfig.OPERATION_DEFAULT_CONFIG + devId, DevConfigInfo.create(listener));
            DefaultConfigBean defaultConfigBean = new DefaultConfigBean();
            defaultConfigBean.setAllConfig(1);
            FunSDK.DevSetConfigByJson(userId, devId, JsonConfig.OPERATION_DEFAULT_CONFIG,
                    HandleConfigData.getSendData(JsonConfig.OPERATION_DEFAULT_CONFIG,
                            "0x1", defaultConfigBean),
                    -1, 20000, seq);
        }
    }

    @Override
    public void checkDevUpgrade(String devId, com.manager.device.DeviceManager.OnDevUpgradeListener listener) {
        init();
        if (listener != null) {
            int seq = devId.hashCode();
            devIdMap.put(seq, devId);
            onDevUpgradeListener = listener;
            FunSDK.DevCheckUpgrade(userId, devId, seq);
        }
    }

    @Override
    public void startDevUpgrade(String devId,int upgradeType, com.manager.device.DeviceManager.OnDevUpgradeListener listener) {
        init();
        if (listener != null) {
            int seq = devId.hashCode();
            devIdMap.put(seq, devId);
            onDevUpgradeListener = listener;
            FunSDK.DevStartUpgrade(userId, devId, upgradeType, seq);
        }
    }

    @Override
    public void startDevUpgradeByLocalFile(String devId, String fileName, com.manager.device.DeviceManager.OnDevUpgradeListener listener) {
        init();
        if (listener != null) {
            int seq = devId.hashCode();
            devIdMap.put(seq, devId);
            onDevUpgradeListener = listener;
            FunSDK.DevStartUpgradeByFile(userId, devId,fileName, seq);
        }
    }

    @Override
    public void switchDevNetworkMode(String devId,String action, com.manager.device.DeviceManager.OnDevManagerListener listener) {
        init();
        if (listener != null) {
            int seq = devId.hashCode();
            devIdMap.put(seq, devId);
            listenerMap.put(APP_JsonConfig.CMD_NET_MODE_SWITCH + devId, DevConfigInfo.create(listener));
            JSONObject jsonObj = new JSONObject();
            JSONObject subJsonObj = new JSONObject();
            try {
                subJsonObj.put("Action", action);
                jsonObj.put("Name", APP_JsonConfig.CMD_NET_MODE_SWITCH );
                jsonObj.put(APP_JsonConfig.CMD_NET_MODE_SWITCH , subJsonObj);
                FunSDK.DevCmdGeneral(userId,devId,1450,APP_JsonConfig.CMD_NET_MODE_SWITCH,
                        0,timeOut,jsonObj.toString().getBytes(),0,seq);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void setTimeOut(int timeOut) {
        this.timeOut = timeOut;
    }

    @Override
    public void getConfigFromDev(String devId, com.manager.device.DeviceManager.OnDevManagerListener listener, String jsonName, String... field) {
        init();
        synchronized (listenerMap) {
            if (listenerMap.containsKey(jsonName + devId)) {
                DevConfigInfo devConfigInfo = listenerMap.get(jsonName + devId);
                if (devConfigInfo != null) {
                    devConfigInfo.addListener(listener, field);
                }
            } else if (StringUtils.contrast(jsonName,JsonConfig.CMD_ENCYPT_CHIP_INFO)) {
                listenerMap.put(jsonName + devId, DevConfigInfo.create(listener, field));
                int seq = devId.hashCode();
                devIdMap.put(seq, devId);
                FunSDK.DevCmdGeneral(userId,devId, EncyptChipInfoBean.CMD,
                        JsonConfig.CMD_ENCYPT_CHIP_INFO,-1,timeOut,null,0,seq);
            } else if (StringUtils.contrast(jsonName,JsonConfig.SYSTEM_EX_INFO)) {
                listenerMap.put(jsonName + devId, DevConfigInfo.create(listener, field));
                int seq = devId.hashCode();
                devIdMap.put(seq, devId);
                FunSDK.DevCmdGeneral(userId,devId, SystemInfoExBean.CMD_ID,
                        JsonConfig.SYSTEM_EX_INFO,-1,timeOut,null,0,seq);
            } else {
                listenerMap.put(jsonName + devId, DevConfigInfo.create(listener, field));
                int seq = devId.hashCode();
                devIdMap.put(seq, devId);
                FunSDK.DevGetConfigByJson(userId, devId, jsonName, 1024, -1, timeOut, seq);
            }
        }
    }

    @Override
    public int OnFunSDKResult(Message msg, MsgContent ex) {
        try {
            String devId = devIdMap.get(ex.seq);
            switch (msg.what) {
                case EUIMSG.DEV_LOGIN: {
                    DevConfigInfo resultInfo = listenerMap.get(APP_JsonConfig.DEV_LOGIN + devId);
                    if (null != resultInfo) {
                        if (msg.arg1 >= 0) {
                            resultInfo.getListener().onSuccess(devId, OPERA_LOGIN_DEV, null);
                        } else {
                            resultInfo.getListener().onFailed(devId, msg.what, APP_JsonConfig.DEV_LOGIN, msg.arg1);
                        }
                    }
                    break;
                }
                case EUIMSG.DEV_GET_CHN_NAME: {
                    DevConfigInfo resultInfo = listenerMap.get(APP_JsonConfig.DEV_GET_CHANNEL_INFO + devId);
                    if (null != resultInfo) {
                        if (msg.arg1 >= 0) {
                            SDK_ChannelNameConfigAll channelNameConfigAll = new SDK_ChannelNameConfigAll();
                            G.BytesToObj(channelNameConfigAll, ex.pData);
                            channelNameConfigAll.nChnCount = msg.arg1;
                            XMDevInfo xmDevInfo = DevDataCenter.getInstance().getDevInfo(devId);
                            if (xmDevInfo != null) {
                                SDBDeviceInfo sdbDeviceInfo = xmDevInfo.getSdbDevInfo();
                                if (sdbDeviceInfo != null) {
                                    sdbDeviceInfo.setChannel(channelNameConfigAll);
                                }
                            }
                            resultInfo.getListener().onSuccess(devId, OPERA_GET_CONFIG_DEV, channelNameConfigAll);
                            listenerMap.remove(APP_JsonConfig.DEV_GET_CHANNEL_INFO + devId);
                        } else {
                            resultInfo.getListener().onFailed(devId, msg.what, APP_JsonConfig.DEV_GET_CHANNEL_INFO, msg.arg1);
                        }
                    }
                }
                break;
                case EUIMSG.DEV_GET_JSON: {
                    synchronized (listenerMap) {
                        if (StringUtils.contrast(ex.str, JsonConfig.SYSTEM_INFO)) {
                            if (msg.arg1 >= 0) {
                                HandleConfigData data = new HandleConfigData();
                                data.getDataObj(G.ToString(ex.pData), SystemInfoBean.class);
                                SystemInfoBean infoBean = (SystemInfoBean) data.getObj();
                                infoBean.setNetConnectMode(msg.arg2);
                                devDataCenter.setSystemInfo(devId, infoBean);
                                DevConfigInfo resultInfo = listenerMap.get(APP_JsonConfig.DEV_LOGIN + devId);
                                if (resultInfo != null) {
                                    resultInfo.getListener().onSuccess(devId, OPERA_GET_CONFIG_DEV, infoBean);
                                    listenerMap.remove(APP_JsonConfig.DEV_LOGIN + devId);
                                } else {
                                    dealWithResultToListener(devId, listenerMap.get(JsonConfig.SYSTEM_INFO + devId), infoBean);
                                }
                            } else {
                                DevConfigInfo resultInfo = listenerMap.get(APP_JsonConfig.DEV_LOGIN + devId);
                                if (resultInfo != null) {
                                    resultInfo.getListener().onFailed(devId, msg.what, JsonConfig.SYSTEM_INFO, msg.arg1);
                                    listenerMap.remove(APP_JsonConfig.DEV_LOGIN + devId);
                                } else {
                                    resultInfo = listenerMap.get(JsonConfig.SYSTEM_INFO + devId);
                                    if (null != resultInfo) {
                                        resultInfo.getListener().onFailed(devId, msg.what, JsonConfig.SYSTEM_INFO, msg.arg1);
                                    }
                                    listenerMap.remove(JsonConfig.SYSTEM_INFO + devId);
                                }
                            }

                        } else if (StringUtils.contrast(ex.str, JsonConfig.SYSTEM_FUNCTION)) {
                            if (msg.arg1 >= 0) {
                                HandleConfigData data = new HandleConfigData();
                                data.getDataObj(G.ToString(ex.pData), SystemFunctionBean.class);
                                SystemFunctionBean infoBean = (SystemFunctionBean) data.getObj();
                                devDataCenter.setSystemFunction(devId, infoBean);
                                dealWithResultToListener(devId, listenerMap.get(JsonConfig.SYSTEM_FUNCTION + devId), infoBean);
                            } else {
                                DevConfigInfo resultInfo = listenerMap.get(JsonConfig.SYSTEM_FUNCTION + devId);
                                if (null != resultInfo) {
                                    resultInfo.getListener().onFailed(devId, msg.what, JsonConfig.SYSTEM_FUNCTION, msg.arg1);
                                }
                            }
                            listenerMap.remove(JsonConfig.SYSTEM_FUNCTION + devId);
                        } else if (StringUtils.contrast(ex.str, JsonConfig.CFG_WIDEOWIDGET)
                                && listenerMap.containsKey(APP_JsonConfig.MODIFY_DEV_NAME_FROM_DEV + devId)) {
                            if (msg.arg1 >= 0) {
                                DevConfigInfo resultInfo = listenerMap.get(APP_JsonConfig.MODIFY_DEV_NAME_FROM_DEV + devId);
                                if (resultInfo != null) {
                                    HandleConfigData data = new HandleConfigData();
                                    if (data.getDataObj(G.ToString(ex.pData), VideoWidgetBean.class)) {
                                        VideoWidgetBean bean = (VideoWidgetBean) data.getObj();
                                        if (bean != null) {
                                            bean.getChannelTitle().setName((String) resultInfo.getCfgInfo());
                                            FunSDK.DevSetConfigByJson(userId, devId, ex.str,
                                                    data.getSendData(DevConfigManager.getCfgJsonFullName(ex.str, resultInfo.getChnId()),
                                                            bean), resultInfo.getChnId(), timeOut, ex.seq);
                                            FunSDK.DevCmdGeneral(userId, devId, 1048, JsonConfig.CFG_CHANNELTITLE, -1, timeOut,
                                                    null, 10, ex.seq);
                                            break;
                                        }
                                    }
                                }
                            }
                            DevConfigInfo resultInfo = listenerMap.get(APP_JsonConfig.MODIFY_DEV_NAME_FROM_DEV + devId);
                            if (null != resultInfo) {
                                resultInfo.getListener().onFailed(devId, msg.what, APP_JsonConfig.MODIFY_DEV_NAME_FROM_DEV, msg.arg1);
                            }
                            listenerMap.remove(APP_JsonConfig.MODIFY_DEV_NAME_FROM_DEV + devId);
                        } else if (StringUtils.contrast(ex.str, JsonConfig.GENERAL_LOCATION)
                                && listenerMap.containsKey(APP_JsonConfig.SYNC_DEV_TIME_ZONE + devId)) {
                            DevConfigInfo resultInfo = listenerMap.get(APP_JsonConfig.SYNC_DEV_TIME_ZONE + devId);
                            resultInfo.setLastConfig(true);
                            if (msg.arg1 >= 0) {
                                HandleConfigData data = new HandleConfigData();
                                if (data.getDataObj(G.ToString(ex.pData), LocationBean.class)) {
                                    LocationBean locationBean = (LocationBean) data.getObj();
                                    if (locationBean != null) {
                                        DayLightTimeBean dayLightTimeBean = XUtils.getDayLightTimeInfo(TimeZone.getDefault());
                                        if (dayLightTimeBean != null) {
                                            if (dayLightTimeBean.useDLT) {
                                                locationBean.setdSTRule("On");
                                                DSTimeBean dstStart = new DSTimeBean();
                                                dstStart.setYear(dayLightTimeBean.year);
                                                dstStart.setMonth(dayLightTimeBean.beginMonth);
                                                dstStart.setDay(dayLightTimeBean.beginDay);
                                                DSTimeBean dstEnd = new DSTimeBean();
                                                dstEnd.setYear(dayLightTimeBean.beginMonth > dayLightTimeBean.endMonth
                                                        ? dayLightTimeBean.year + 1 : dayLightTimeBean.year);
                                                dstEnd.setMonth(dayLightTimeBean.endMonth);
                                                dstEnd.setDay(dayLightTimeBean.endDay);
                                                locationBean.setdSTStart(dstStart);
                                                locationBean.setdSTEnd(dstEnd);
                                            } else {
                                                locationBean.setdSTRule("Off");
                                            }
                                        }
                                        FunSDK.DevSetConfigByJson(userId, devId, JsonConfig.GENERAL_LOCATION,
                                                HandleConfigData.getSendData(JsonConfig.GENERAL_LOCATION, "0x02", locationBean),
                                                -1, timeOut, ex.seq);
                                    }
                                }
                            }
                        }
//                    else {
//                        DevConfigInfo resultInfo = listenerMap.get(ex.str + devId);
//                        if (null != resultInfo) {
//                            Type[] t = resultInfo.getListener().getClass().getGenericInterfaces();
//                            if (t[0] instanceof ParameterizedType) {
//                                Type[] t2 = ((ParameterizedType) t[0]).getActualTypeArguments();
//                                HandleConfigData data = new HandleConfigData();
//                                data.getDataObj(G.ToString(ex.pData), (Class<?>) t2[0]);
//                                resultInfo.getListener().onSuccess(devId, OPERA_GET_CONFIG_DEV, data.getObj());
//                            } else {
//                                resultInfo.getListener().onSuccess(devId, OPERA_GET_CONFIG_DEV, G.ToString(ex.pData));
//                            }
//                        }
//                        listenerMap.remove(JsonConfig.CFG_WIDEOWIDGET + devId);
//                    }
                    }
                    break;
                }
                case EUIMSG.DEV_SET_JSON: {
                    if (StringUtils.contrast(ex.str, APP_JsonConfig.MODIFY_DEV_PWD_FROM_DEV)) {
                        DevConfigInfo resultInfo = listenerMap.get(ex.str + devId);
                        if (resultInfo != null) {
                            Bundle bundle = (Bundle) resultInfo.getCfgInfo();
                            if (bundle != null) {
                                FunSDK.DevSetLocalPwd(devId,
                                        bundle.getString("userName"),
                                        bundle.getString("password"));
                            }
                            if (msg.arg1 >= 0) {
                                resultInfo.getListener().onSuccess(devId, OPERA_SET_CONFIG_DEV, 0);
                            } else {
                                resultInfo.getListener().onFailed(devId, msg.what, APP_JsonConfig.MODIFY_DEV_PWD_FROM_DEV, msg.arg1);
                            }
                        }
                        listenerMap.remove(APP_JsonConfig.MODIFY_DEV_PWD_FROM_DEV + devId);
                    } else if (StringUtils.contrast(ex.str, JsonConfig.SYSTEM_TIMEZONE)
                            && listenerMap.containsKey(APP_JsonConfig.SYNC_DEV_TIME_ZONE + devId)) {
                        DevConfigInfo resultInfo = listenerMap.get(APP_JsonConfig.SYNC_DEV_TIME_ZONE + devId);
                        if (resultInfo != null) {
                            if (resultInfo.isLastConfig()) {
                                if (msg.arg1 >= 0) {
                                    resultInfo.getListener().onSuccess(devId, OPERA_SET_CONFIG_DEV, 0);
                                } else {
                                    resultInfo.getListener().onFailed(devId, msg.what, APP_JsonConfig.SYNC_DEV_TIME_ZONE, msg.arg1);
                                }
                                listenerMap.remove(APP_JsonConfig.SYNC_DEV_TIME_ZONE + devId);
                            }
                        }
                    } else if (StringUtils.contrast(ex.str, JsonConfig.GENERAL_LOCATION)
                            && listenerMap.containsKey(APP_JsonConfig.SYNC_DEV_TIME_ZONE + devId)) {
                        DevConfigInfo resultInfo = listenerMap.get(APP_JsonConfig.SYNC_DEV_TIME_ZONE + devId);
                        if (resultInfo != null) {
                            if (resultInfo.isLastConfig()) {
                                if (msg.arg1 >= 0) {
                                    resultInfo.getListener().onSuccess(devId, OPERA_SET_CONFIG_DEV, 0);
                                } else {
                                    resultInfo.getListener().onFailed(devId, msg.what, APP_JsonConfig.SYNC_DEV_TIME_ZONE, msg.arg1);
                                }
                                listenerMap.remove(APP_JsonConfig.SYNC_DEV_TIME_ZONE + devId);
                            }
                        }
                    } else if (StringUtils.contrast(ex.str, JsonConfig.OPTIME_SET)) {
                        DevConfigInfo resultInfo = listenerMap.get(JsonConfig.OPTIME_SET + devId);
                        if (resultInfo != null) {
                            if (msg.arg1 >= 0) {
                                resultInfo.getListener().onSuccess(devId, OPERA_SET_CONFIG_DEV, 0);
                            } else {
                                resultInfo.getListener().onFailed(devId, msg.what, JsonConfig.OPTIME_SET, msg.arg1);
                            }
                        }
                        listenerMap.remove(JsonConfig.OPTIME_SET + devId);
                    } else {
                        DevConfigInfo resultInfo = listenerMap.get(ex.str + devId);
                        if (resultInfo != null) {
                            if (msg.arg1 >= 0) {
                                resultInfo.getListener().onSuccess(devId, OPERA_SET_CONFIG_DEV, 0);
                            } else {
                                resultInfo.getListener().onFailed(devId, msg.what, ex.str, msg.arg1);
                            }
                        }
                        listenerMap.remove(ex.str + devId);
                    }
                    break;
                }
                case EUIMSG.DEV_CMD_EN: {
                    if (StringUtils.contrast(ex.str, JsonConfig.CFG_CHANNELTITLE)
                            && listenerMap.containsKey(APP_JsonConfig.MODIFY_DEV_NAME_FROM_DEV + devId)) {
                        DevConfigInfo resultInfo = listenerMap.get(APP_JsonConfig.MODIFY_DEV_NAME_FROM_DEV + devId);
                        if (msg.arg1 >= 0 && ex.pData != null) {
                            if (resultInfo != null) {
                                if (!resultInfo.isLastConfig()) {
                                    resultInfo.setLastConfig(true);
                                    HandleConfigData data = new HandleConfigData();
                                    if (data.getDataObj(G.ToString(ex.pData), String.class)) {
                                        List<String> list = (List<String>) data.getObj();
                                        if (list != null) {
                                            list.set(resultInfo.getChnId(), (String) resultInfo.getCfgInfo());
                                            FunSDK.DevCmdGeneral(userId, devId, 1048, JsonConfig.CFG_CHANNELTITLE,
                                                    -1, timeOut, data.getSendData(JsonConfig.CFG_CHANNELTITLE, list).getBytes(), -1, ex.seq);
                                            break;
                                        }
                                    }
                                } else {
                                    if (null != resultInfo) {
                                        resultInfo.getListener().onSuccess(devId, OPERA_SET_CONFIG_DEV, resultInfo.getCfgInfo());
                                    }
                                    listenerMap.remove(APP_JsonConfig.MODIFY_DEV_NAME_FROM_DEV + devId);
                                    break;
                                }
                            }
                        }
                        if (null != resultInfo) {
                            resultInfo.getListener().onFailed(devId, msg.what, APP_JsonConfig.MODIFY_DEV_NAME_FROM_DEV, msg.arg1);
                        }
                        listenerMap.remove(APP_JsonConfig.MODIFY_DEV_NAME_FROM_DEV + devId);
                    } else if (StringUtils.contrast(ex.str, JsonConfig.CMD_ENCYPT_CHIP_INFO)) {
                        DevConfigInfo resultInfo = listenerMap.get(JsonConfig.CMD_ENCYPT_CHIP_INFO + devId);
                        if (msg.arg1 >= 0) {
                            if (resultInfo != null) {
                                HandleConfigData data = new HandleConfigData();
                                if (data.getDataObj(G.ToString(ex.pData), EncyptChipInfoBean.class)) {
                                    EncyptChipInfoBean encyptChipInfoBean = (EncyptChipInfoBean) data.getObj();
                                    if (encyptChipInfoBean != null) {
                                        resultInfo.getListener().onSuccess(devId, EncyptChipInfoBean.CMD, encyptChipInfoBean.getoEMID());
                                    }
                                }
                            }
                        } else {
                            if (resultInfo != null) {
                                resultInfo.getListener().onFailed(devId, EncyptChipInfoBean.CMD,
                                        JsonConfig.CMD_ENCYPT_CHIP_INFO, msg.arg1);
                            }
                        }
                        listenerMap.remove(JsonConfig.CMD_ENCYPT_CHIP_INFO + devId);
                    } else if (StringUtils.contrast(ex.str, JsonConfig.SYSTEM_EX_INFO)) {
                        if (msg.arg1 >= 0) {
                            HandleConfigData data = new HandleConfigData();
                            data.getDataObj(G.ToString(ex.pData), SystemInfoExBean.class);
                            SystemInfoExBean infoBean = (SystemInfoExBean) data.getObj();
                            devDataCenter.setSystemExInfo(devId, infoBean);
                            dealWithResultToListener(devId, listenerMap.get(JsonConfig.SYSTEM_EX_INFO + devId), infoBean);
                        } else {
                            DevConfigInfo resultInfo = listenerMap.get(JsonConfig.SYSTEM_EX_INFO + devId);
                            if (null != resultInfo) {
                                resultInfo.getListener().onFailed(devId, msg.what, JsonConfig.SYSTEM_EX_INFO, msg.arg1);
                            }
                        }
                        listenerMap.remove(JsonConfig.SYSTEM_EX_INFO + devId);
                    } else {
                        DevConfigInfo resultInfo = listenerMap.get(ex.str + devId);
                        if (resultInfo != null) {
                            if (msg.arg1 >= 0) {
                                resultInfo.getListener().onSuccess(devId, OPERA_CMD, 0);
                            } else {
                                resultInfo.getListener().onFailed(devId, msg.what, ex.str, msg.arg1);
                            }
                        }
                        listenerMap.remove(ex.str + devId);
                    }
                    break;
                }
                case EUIMSG.DEV_SEARCH_DEVICES: {
                    int length = msg.arg2;
                    if (length > 0) {
                        SDK_CONFIG_NET_COMMON_V2[] searchResult = new SDK_CONFIG_NET_COMMON_V2[length];
                        for (int i = 0; i < searchResult.length; i++) {
                            searchResult[i] = new SDK_CONFIG_NET_COMMON_V2();
                        }
                        G.BytesToObj(searchResult, ex.pData);
                        lanDevList = new ArrayList<>();
                        for (SDK_CONFIG_NET_COMMON_V2 devinfo : searchResult) {
                            if (devinfo != null) {
                                XMDevInfo xmDevInfo = new XMDevInfo();
                                xmDevInfo.lanDevInfoToXMDevInfo(devinfo);
                                lanDevList.add(xmDevInfo);
                                DevDataCenter.getInstance().addDev(xmDevInfo);
                            }
                        }
                    } else {
                        lanDevList = null;
                    }
                    if (onSearchLocalDevListener != null) {
                        onSearchLocalDevListener.onSearchLocalDevResult(lanDevList);
                    }
                    break;
                }
                case EUIMSG.DEV_AP_CONFIG: {
                    XMDevInfo xmDevInfo = null;
                    if (msg.arg1 >= 0) {
                        SDK_CONFIG_NET_COMMON_V2 common = new SDK_CONFIG_NET_COMMON_V2();
                        G.BytesToObj(common, ex.pData);
                        xmDevInfo = new XMDevInfo();
                        xmDevInfo.lanDevInfoToXMDevInfo(common);
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                stopQuickSetWiFi();
                            }
                        }).start();
                        if (onQuickSetWiFiListener != null) {
                            onQuickSetWiFiListener.onQuickSetResult(xmDevInfo, 0);
                        }
                    } else {
                        if (onQuickSetWiFiListener != null) {
                            onQuickSetWiFiListener.onQuickSetResult(null, msg.arg1);
                        }
                    }

                    break;
                }
                case EUIMSG.DEV_SET_WIFI_CFG: {
                    if (msg.arg1 == DEVICE_LINK_ROUTER_SUCCESS) {
                        SDK_CONFIG_NET_COMMON_V2 common = new SDK_CONFIG_NET_COMMON_V2();
                        G.BytesToObj(common, ex.pData);
                        XMDevInfo xmDevInfo = new XMDevInfo();
                        xmDevInfo.lanDevInfoToXMDevInfo(common);
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                stopQuickSetWiFi();
                            }
                        }).start();
                        if (onDevWiFiSetListener != null) {
                            onDevWiFiSetListener.onDevWiFiSetResult(xmDevInfo);
                        }
                    } else {
                        if (onDevWiFiSetListener != null) {
                            onDevWiFiSetListener.onDevWiFiSetState(msg.arg1);
                        }
                    }

                    break;
                }
                case EUIMSG.DEV_CHECK_UPGRADE: {
                    if (onDevUpgradeListener != null) {
                        onDevUpgradeListener.onCheckUpgradeResult(msg.arg1, msg.arg1);
                    }
                    break;
                }
                case EUIMSG.DEV_START_UPGRADE: {
                    if (onDevUpgradeListener != null) {
                        onDevUpgradeListener.onUpgradeProgress(0, 0, msg.arg1);
                    }
                    break;
                }
                case EUIMSG.DEV_ON_UPGRADE_PROGRESS: {
                    if (onDevUpgradeListener != null) {
                        onDevUpgradeListener.onUpgradeProgress(msg.arg1, msg.arg2, msg.arg1);
                    }
                    break;
                }
            }
        }catch (Exception e){
            Log.d("Monitor", "OnFunSDKResult: "+e.getMessage());
        }
        return 0;
    }

    private void dealWithResultToListener(String devId, DevConfigInfo resultInfo, Object obj) {
        if (null != resultInfo && null != obj) {
            Class<?> _class = obj.getClass();
            try {
                String[][] fields = resultInfo.getFields();
                for (String[] field : fields) {
                    com.manager.device.DeviceManager.OnDevManagerListener listener = resultInfo.getListener(field);
                    if (field != null && listener != null) {
                        dealWithField(devId,obj,field,_class,listener);
                    }
                }
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            }
        }
    }

    private void dealWithField(String devId, Object obj, String[] fieldNames,
                               Class<?> _class, com.manager.device.DeviceManager.OnDevManagerListener listener) throws NoSuchMethodException {
        if (fieldNames.length == 1) {
            if (fieldNames[0].startsWith("is") || fieldNames[0].startsWith("get")) {
                Method method = _class.getMethod(fieldNames[0], (Class[]) null);
                if (method != null) {
                    try {
                        Object result = method.invoke(obj);
                        listener.onSuccess(devId, 0, result);
                        return;
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    } catch (InvocationTargetException e) {
                        e.printStackTrace();
                    }
                }
            } else {
                try {
                    Field field = _class.getField(fieldNames[0]);
                    if (null != field && field.getType() == Boolean.TYPE) {
                        try {
                            Boolean result = (Boolean) field.get(obj);
                            listener.onSuccess(devId, 0, result);
                            return;
                        } catch (IllegalAccessException e) {
                            e.printStackTrace();
                        }
                    }
                } catch (NoSuchFieldException e) {
                    e.printStackTrace();
                }
            }
        } else if (fieldNames.length > 1){
            try {
                Field field = _class.getField(fieldNames[0]);
                if (field.getClass() instanceof Class) {
                    try {
                        Object _obj = field.get(obj);
                        if (null != _obj) {
                            _class = _obj.getClass();
                            field = _class.getField(fieldNames[1]);
                            if (null != field && field.getType() == Boolean.TYPE) {
                                Object result = field.get(_obj);
                                listener.onSuccess(devId, 0, result);
                                return;
                            }
                        }
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    }
                }
            } catch (NoSuchFieldException e) {
                e.printStackTrace();
            }
        }else {
            listener.onSuccess(devId, 0, obj);
        }
    }

    public interface OnDevManagerListener<T> {
        void onSuccess(String devId, int operationType, T result);
        void onFailed(String devId, int msgId, String jsonName, int errorId);
    }

    public interface OnSearchLocalDevListener {
        void onSearchLocalDevResult(List<XMDevInfo> localDevList);
    }

    public interface OnQuickSetWiFiListener {
        void onQuickSetResult(XMDevInfo xmDevInfo,int errorId);
    }

    public interface OnDevWiFiSetListener {
        void onDevWiFiSetState(int result);
        void onDevWiFiSetResult(XMDevInfo xmDevInfo);
    }

    public interface OnDevUpgradeListener {
        void onCheckUpgradeResult(int upgradeType,int errorId);
        void onUpgradeProgress(int state,int progress,int errorId);
    }
}
